<template>
  <div>
      <!-- 头部面包屑区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图主体部分 -->
        <el-card>
            <!-- 消息提示部分 -->
            <el-alert
                center
                title="添加商品信息"
                type="info"
                show-icon>
            </el-alert>

            <!-- 步骤条部分 -->
            <el-steps 
            :space="200" 
            :active="activeIndex - 0" 
            finish-status="success"
            align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>

            <!-- 左侧导航区域 -->
            <el-form 
            :model="addFormData" :rules="addFormDataRules" 
            ref="addFormRef" label-width="100px"
            label-position="top"
            >
                <el-tabs 
                :tab-position="'left'" 
                v-model="activeIndex"
                :before-leave="beforeTabLeave"
                @tab-click="clickTab">
                    <el-tab-pane 
                    label="基本信息" 
                    name="0">

                        <el-form-item 
                        label="商品名称"
                        prop="goods_name">
                            <el-input v-model="addFormData.goods_name">
                            </el-input>
                        </el-form-item>
                        <el-form-item 
                        label="商品价格"
                        prop="goods_price">
                            <el-input v-model.number="addFormData.goods_price"
                            type="number">
                            </el-input>
                        </el-form-item>
                        <el-form-item 
                        label="商品重量"
                        prop="goods_weight">
                            <el-input 
                            v-model.number="addFormData.goods_weight"
                            type="number"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item 
                        label="商品数量"
                        prop="goods_number">
                            <el-input v-model.number="addFormData.goods_number"
                            type="number">
                            </el-input>
                        </el-form-item>

                        <el-form-item 
                        label="商品分类"
                        prop="goods_cat">
                        <!-- 
                            options 数据源
                            props 数据源的配置选项
                            v-model 双向绑定的当前选中的实际值
                            @change 当选中项发生改变触发
                         -->
                            <el-cascader
                            expand-trigger="hover"
                            :options="goodsCatList"
                            :props="goodsCatsProps"
                            v-model="addFormData.goods_cat"
                            @change="handleChange">
                            </el-cascader>
                        </el-form-item>

                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item 
                        :label="item.attr_name" 
                        v-for="item in manyTableData" :key="item.attr_id">
                            <el-checkbox-group 
                            v-model="item.attr_vals">
                                <el-checkbox 
                                border
                                v-for="(cb,i) in item.attr_vals"
                                :key="i"
                                :label="cb">
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item 
                        :label="item.attr_name" 
                        v-for="item in onlyTableData" :key="item.attr_id">
                            <el-input 
                            v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                            action="http://127.0.0.1:8888/api/private/v1/upload"
                            :headers="uploadHead"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-success="uploadSuccess"
                            list-type="picture">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor
                            v-model="addFormData.goods_introduce"
                        >
                        </quill-editor>
                        <el-button 
                        type="primary"
                        class="addGoods"
                        @click="addGoods">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <!-- 预览图片 -->
        <el-dialog
        title="图片预览"
        :visible.sync="isImg"
        width="50%"
        :modal-append-to-body="false"
        @close="dialogClose">
            <img class="imgClass" :src="imgUrl" alt="">
        </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
    name:'Add',
    data(){
        return {
            // 定义一个参数用来存储当前步骤
            activeIndex:'0',
            // 用来存储整个form表单的数据对象
            addFormData:{
                goods_name:'',
                goods_price:'',
                goods_weight:'',
                goods_number:'',
                goods_cat:[],
                pics:[],
                // 商品的详情描述
                goods_introduce:'',
                attrs:[]
            },
            // 用来存储整个form表单的校验规则
            addFormDataRules:{
                goods_name:[
                    {required: true, message:'请输入商品名称', trigger: 'blur'}
                ],
                goods_price:[
                    {required: true, message:'请输入商品价格', trigger: 'blur'}
                ],
                goods_weight:[
                    {required: true, message:'请输入商品重量', trigger: 'blur'}
                ],
                goods_number:[
                    {required: true, message:'请输入商品数量', trigger: 'blur'}
                ],
                goods_cat:[
                    {required: true, message:'请选择商品分类', trigger: 'blur'}
                ]
            },
            // 用于存储基本信息中商品分类的数据对象
            goodsCatList:[],
            
            // 用于存储基本信息中的商品分类数据的配置对象
            goodsCatsProps:{
                // 展示的数据
                label:'cat_name',
                // 实际选中的值
                value:'cat_id',
                // 通过哪个属性嵌套的
                children:'children'
            },
            // 用于存储商品参数
            manyTableData:[],
            // 用于存储商品属性
            onlyTableData:[],
            // 上传图像请求头携带的参数
            uploadHead:{
                Authorization:window.sessionStorage.getItem('token')
            },
            // 预览图片url
            imgUrl:'',
            // 控制显示与隐藏图片预览dialog
            isImg:false,

            // 商品内容

        }
    },
    methods: {
        // 获取商品分类列表
        async getCatList(){
            const {data:res} = await this.$axios.get('categories')
            if(res.meta.status!==200) this.$message.error('获取商品分类列表失败')
            console.log(res);
            this.goodsCatList = res.data;
        },
        // 当用户切换商品分类时触发
        handleChange(){
            if(this.addFormData.goods_cat.length!==3) this.addFormData.goods_cat = [];       
        },
        // 当用户切换步骤前触发
        beforeTabLeave(activeName,oldActiveName){
            // console.log(activeName,oldActiveName);
            if(oldActiveName == '0' && this.addFormData.goods_cat.length!==3){
                this.$message.error('请先选择商品分类')
                return false;
            }
        },
        // 当用户单击切换tab时触发
        async clickTab(){
            // console.log(this.activeIndex);
            // 判断当用户点击的tab为1，也就是商品参数
            if(this.activeIndex === '1'){
                const {data:res} = await this.$axios.get(`categories/${this.cateId}/attributes`,{
                    params:{
                        sel:'many'
                    }
                })
                if(res.meta.status!==200) return this.$message.error('商品参数获取失败')
                
                res.data.forEach(item=>{
                    if(item.attr_vals.length!==0){
                        item.attr_vals = item.attr_vals.split(' ')
                    }
                })
                this.manyTableData = res.data;
                console.log(this.manyTableData);
            }else if(this.activeIndex === '2'){
                const {data:res} = await this.$axios.get(`categories/${this.cateId}/attributes`,{
                    params:{
                        sel:'only'
                    }
                })
                if(res.meta.status!==200)return this.$message.error('获取属性列表失败')
                this.onlyTableData = res.data;
                console.log(this.onlyTableData);
            }
        },
        // 当用户点击了已上传的图片预览时触发
        handlePreview(file){
            this.imgUrl = file.response.data.url;
            this.isImg = true;
            
        },
        // 当用户点击删除文件的按钮时触发
        handleRemove(file,fileList){
            const fileUrl = file.response.data.tmp_path;
            const i = this.addFormData.pics.findIndex(x=>x.pic === fileUrl)
            this.addFormData.pics.splice(i,1);
            console.log(this.addFormData.pics);
        },
        // 当用户成功上传图片时触发
        uploadSuccess(response){
            this.addFormData.pics.push({
                pic:response.data.tmp_path
            })
            console.log(this.addFormData.pics);
        },
        // 预览图片dialog对话框关闭时
        dialogClose(){
            this.isImg = false;
        },
        // 商品详情中添加商品按钮
        async addGoods(){
            this.$refs.addFormRef.validate(valid=>{
                if(!valid) return this.$message.error('校验未通过，请填写必要的表单')
            })

            // 发送前需注意，我们的goods_cat需要以字符串,分隔，而不是数组
            // 所以我们需要将goods_cat先转成字符串
            // 在那之前为了避免级联选择器报错，需要先深拷贝一份该goods对象
            
            // 深拷贝一个新表单用于提交添加请求
           const form = _.cloneDeep(this.addFormData);
            // 将其中的cat转换为用,分隔的字符串
            form.goods_cat = form.goods_cat.join(',');
            // 生成many动态参数对象
            this.manyTableData.forEach(item=>{
                const data = {
                    attr_id:item.attr_id,
                    attr_value:item.attr_vals.join(','),
                };
                this.addFormData.attrs.push(data);
            })
            // 生成only静态属性对象
            this.onlyTableData.forEach(item=>{
                const data = {
                    attr_id:item.attr_id,
                    attr_value:item.attr_vals,
                };
                this.addFormData.attrs.push(data);
            })
            form.attrs = this.addFormData.attrs;
            console.log(form);
            // 发起请求
            const {data:res} = await this.$axios.post('goods',form)
            console.log(res);
            if(res.meta.status!==201) return this.$message.error('添加商品失败')

            this.$message.success('添加商品成功');
            this.$router.push('/goods');
        }
    },
    computed:{
        // 当前3级分类的id
        cateId(){
            if(this.addFormData.goods_cat.length === 3){
                return this.addFormData.goods_cat[2];
            }else{
                return null;
            }
        }
    },
    created(row) {
        this.getCatList();

    },
}
</script>

<style scoped lang="less">

.el-checkbox{
    margin: 0 10px 0 0 !important;
}
.imgClass{
    width: 100%;
}
.addGoods{
    margin-top: 15px;
}

</style>